const express = require("express");
const app = express();
const port = 3000; //服务端口
const jwt = require("jsonwebtoken");
const JWT_SECRET_KEY = "JWT_SECRET_KEY";
const Response = require("./utils/Response");
//配置跨域
const cors = require("cors");
app.use(
  cors({
    origin: "*",
  })
);
//解析post请求
app.use(express.urlencoded({ extended: true }));

//自定义token全局验证中间件

const tokenTools = function (req, resp, next) {
  //若请求路径是/user/login 则不拦截 ，直接向后执行即可
  if (req.path == "/user/login") {
    next();
    return;
  }
  let token = req.headers["authorization"];
  try {
    let payload = jwt.verify(token, JWT_SECRET_KEY);
    req.tokenPayload = payload; //将token中存储的值，直接复制给req
  } catch (error) {
    resp.send(Response.error(401, "用户验证失败,请重新登录"));
    return;
  }
  next();
};
app.use(tokenTools);
// 引入外部路由
app.use(require("./router/MovieActor"));
app.use(require("./router/MovieDirector"));
app.use(require("./router/MovieInfo"));
app.use(require("./router/MovieThumb"));
app.use(require("./router/Cinema"));
app.use(require("./router/CinemaRoom"));
app.use(require("./router/ShowingonPlan"));
app.use(require("./router/Admin"));

//接口测试
app.get("/", (req, resp) => {
  resp.send("Hello World");
});
app.listen(port, () => {
  console.log("皮皮陈影院后端服务已启动....");
});
